<template>
  <basic-container>
    <div id="communityBuildingList" v-cloak>
      <el-container>
        <el-main id="el-main">
          <div>
            <!--工具条-->
            <div name="searchColums" id="searchColums">
              <el-form :inline="true" :model="listQuery" size="small" ref="listQuery" class="searchForm">
                <el-form-item class="el-form-item" label="姓名">
                  <el-input name="name" auto-complete="off" v-model="listQuery.name" placeholder="请输入姓名"></el-input>
                </el-form-item>
                <el-form-item class="el-form-item" label="手机号">
                  <el-input name="phone" v-model="listQuery.phone" auto-complete="off" placeholder="请输入手机号"></el-input>
                </el-form-item>
                <el-form-item label="所属部门" prop="deptId">
                  <el-input v-model="listQuery.deptName" size="medium" disabled class="input-with-select">
                    <el-button slot="append" icon="el-icon-search" @click.native="searchDept"></el-button>
                  </el-input>
                </el-form-item>
                <span class="bth_search">
                  <el-form-item>
                    <el-button class="filter-item" type="primary" icon="search" @click="handleFilter">搜索</el-button>
                  </el-form-item>
                  <el-form-item>
                    <el-button @click="resetForm()" icon="el-icon-refresh">重置</el-button>
                  </el-form-item>
                </span>
              </el-form>
            </div>
            <!--toolbar-->
            <el-row id="toolbar">
              <el-col :span="24">
                <div class="grid-content bg-purple-light">
                  <el-button type="primary" size="mini" @click="add()" icon="el-icon-plus">新增</el-button>
                  <!-- <el-button type="primary" size="mini" :disabled="this.sels.length<=1" @click="deleteall()" icon="el-icon-delete">批量删除</el-button> -->
                  <el-button type="primary" size="mini" @click="templeteDown" icon="el-icon-download">模板下载</el-button>
                  <el-button type="primary" size="mini" @click="templeteUp" icon="el-icon-upload">导入</el-button>
                  <el-button size="mini" @click="toggleSelection()">取消选择</el-button>
                </div>
              </el-col>
            </el-row>

            <!--列表-->
            <el-table id="datagrid" @selection-change="handleSelectionChange" ref="tableData" v-loading="listLoading" :data="tableData" empty-text="暂时没有数据哦~" border stripe size="mini" style="width: 100%;">
              <el-table-column align="center" type="selection" width="45"></el-table-column>
              <el-table-column align="center" prop="index" type="index" label="序号" width="50"></el-table-column>
              <el-table-column align="center" prop="name" label="姓名" width="80" show-overflow-tooltip></el-table-column>
              <el-table-column align="center" prop="phone" label="手机号" width="120" show-overflow-tooltip></el-table-column>
              <el-table-column align="center" prop="idCard" label="身份证号" width="160" show-overflow-tooltip></el-table-column>
              <el-table-column align="center" prop="jobNumber" label="工号" width="100" show-overflow-tooltip></el-table-column>
              <el-table-column align="center" prop="deptName" label="部门" width="120" show-overflow-tooltip></el-table-column>
              <el-table-column align="center" prop="roleName" label="角色" width="80" show-overflow-tooltip></el-table-column>
              <el-table-column align="center" label="操作" fixed="right" min-width="290">
                <template slot-scope="scope">
                  <el-button type="success" @click="handleFinger(scope.$index, scope.row)" size="mini">开启指纹采集模式</el-button>
                  <el-button @click="handleEdit(scope.$index, scope.row)" size="mini" icon="el-icon-edit">编辑</el-button>
                  <el-button size="mini" type="danger" @click="deleteConfim(scope.row)" icon="el-icon-delete">删除</el-button>
                  <!--<el-button type="success" size="mini" @click="handleDel(scope.$index, scope.row)">关联房屋</el-button>-->
                </template>
              </el-table-column>
            </el-table>

            <!--工具条-->
            <el-col :span="24" class="toolbar" id="pageDiv">
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
              </el-pagination>
            </el-col>

            <!--新增界面-->
            <el-dialog :title="textMap[dialogStatus]" :visible.sync="addFormVisible" :close-on-click-modal="false">
              <el-form :model="addFormData" prop="addFormData" ref="addFormData" :rules="rules" label-width="100px" size="mini">
                <el-row :span="24">
                  <el-col :span="12">
                    <el-form-item label="姓名" prop="name">
                      <el-input v-model="addFormData.name" auto-complete="off" placeholder="请输入姓名"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="手机号" prop="phone">
                      <el-input v-model="addFormData.phone" auto-complete="off" placeholder="请输入手机号"></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="身份证号" prop="idCard">
                      <el-input v-model="addFormData.idCard" @change="idNoChange" auto-complete="off" placeholder="请输入身份证号"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="所属部门" prop="deptId">
                      <el-input v-model="addFormData.deptName" size="medium" disabled class="input-with-select">
                        <el-button slot="append" icon="el-icon-search" @click.native="handleDept"></el-button>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="性别" prop="sex">
                      <el-radio-group v-model="addFormData.sex">
                        <el-radio label="1">男</el-radio>
                        <el-radio label="2">女</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="年龄" prop="age">
                      <el-input v-model="addFormData.age" auto-complete="off" placeholder="请输入年龄"></el-input>
                    </el-form-item>
                  </el-col>
                  <!-- <el-col :span="12">
                  <el-form-item label="工号" prop="jobNumber">
                    <el-input v-model="addFormData.jobNumber" auto-complete="off" placeholder="请输入工号"></el-input>
                  </el-form-item>
                </el-col> -->
                  <el-col :span="12">
                    <el-form-item label="职位" prop="position">
                      <el-select placeholder="请选择" v-model="addFormData.position">
                        <el-option v-for="item in positions" :key="item.value" :value="item.value" :label="item.label"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="学历" prop="education">
                      <el-select placeholder="请选择" v-model="addFormData.education">
                        <el-option v-for="item in educations" :key="item.value" :value="item.value" :label="item.label"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <!-- <el-col :span="12">
                  <el-form-item label="工作年限" prop="working">
                    <el-select v-model="addFormData.working" class="filter-item" placeholder="请选择">
                      <el-option v-for="item in workings" :key="item.value" :value="item.value" :label="item.label"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col> -->
                  <!-- <el-col :span="12">
                  <el-form-item label="是否缴纳保险" prop="insurance">
                    <el-radio-group v-model="addFormData.insurance">
                      <el-radio v-for="item in insurances" :key="item.value" :value="item.value" :label="item.label"></el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col> -->
                  <!-- <el-col :span="12">
                  <el-form-item label="职级工资" prop="wages">
                    <el-input v-model.number="addFormData.wages" auto-complete="off" placeholder="请输入职级工资"></el-input>
                  </el-form-item>
                </el-col> -->
                  <el-col :span="24">
                    <el-form-item label="所属角色" prop="roleId">
                      <el-input v-model="addFormData.roleName" size="medium" disabled class="input-with-select">
                        <el-button slot="append" icon="el-icon-search" @click.native="showRoleSelect"></el-button>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <!-- <el-col :span="12">
                  <el-form-item label="合同签订日期" prop="contract_start">
                    <el-date-picker type="date" v-model="addFormData.contractStart" placeholder="选择合同签订时间"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="合同结束日期" prop="contract_end">
                    <el-date-picker type="date" v-model="addFormData.contractEnd" placeholder="选择合同结束时间"></el-date-picker>
                  </el-form-item>
                </el-col> -->
                </el-row>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click.native="addFormVisible = false">取消</el-button>
                <el-button v-if="dialogStatus=='create'" type="primary" @click="create('addFormData')" :loading="editLoading">提 交</el-button>
                <el-button v-else type="primary" @click="update('addFormData')" :loading="editLoading"> 修 改</el-button>
                <!--<el-button type="primary" @click="resetForm('addForm')">重置</el-button>-->
              </div>
            </el-dialog>
            <!-- 选择部门 -->
            <el-dialog title="选择部门" :visible.sync="dialogDeptVisible" :close-on-click-modal="false">
              <!-- <el-tree class="filter-tree" ref="tree" :data="treeDeptData" check-strictly node-key="id" highlight-current :props="defaultProps" show-checkbox default-expand-all>
            </el-tree> -->
              <el-tree class="filter-tree" :data="treeDeptData" :props="defaultProps" highlight-current @node-click="handleNodeClick"></el-tree>
              <div slot="footer" class="dialog-footer">
                <el-button v-if="dialogStatus=='search'" type="primary" @click="closeDept">选 择</el-button>
                <el-button v-else type="primary" @click="closeDept">更 新</el-button>
              </div>
            </el-dialog>
            <!--角色选择界面-->
            <el-dialog title="门禁角色选择" :visible.sync="roleSelectVisible" :close-on-click-modal="false">
              <div style="height: 380px!important;position:relative">
                <div style="height: 260px;overflow: auto;">
                  <roleTree ref="role_tree" @treeNode-click="roleTreeNodeClick"></roleTree>
                </div>
                <div>
                  <el-tag type="info" style="position:absolute;bottom: 95px;" size="small">选择的角色</el-tag>
                </div>
                <el-input type="textarea" style="position:absolute;bottom: 0px;" disabled :rows="4" v-model="textarea_role"></el-input>
              </div>
              <div slot="footer" class="dialog-footer">
                <el-button @click.native="roleSelectVisible = false">取消</el-button>
                <el-button type="primary" @click.native="roleSelectSubmit" :loading="addLoading">确定</el-button>
              </div>
            </el-dialog>
            <!--删除确认框-->
            <el-dialog title="删除原因" :visible.sync="deleteDialog" :close-on-click-modal="false" width="30%">
              <el-form :model="deleteData" size="small">
                <el-col :span="24">
                  <el-form-item>
                    <el-select placeholder="请选择" v-model="deleteData.quit">
                      <el-option value="1" label="离职"></el-option>
                      <el-option value="0" label="信息填写错误"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click.native="deleteDialog = false">取消</el-button>
                <el-button type="primary" @click.native="deletes()" :loading="addLoading">确定</el-button>
              </div>
            </el-dialog>
            <!--导入界面-->
            <el-dialog title="导入" :visible.sync="importFormVisible" :close-on-click-modal="false">
              <el-upload class="upload-demo" ref="upload" accept="xls,xlsx" action="admin/employeeInfo/upload" :on-preview="handlePreview" :on-remove="handleRemove" :on-success="handleSuccess" :before-upload="beforeAvatarUpload" :file-list="fileList" :headers="uploadHeader" :data="uploadParams" :auto-upload="false">
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload" :loading="addLoading">上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件</div>
              </el-upload>
            </el-dialog>
          </div>
        </el-main>
      </el-container>
      <!-- <employee ref="employee"></employee> -->
    </div>
  </basic-container>
</template>
<style lang="scss" scoped>
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;
    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }
    .highlighted .addr {
      color: #ddd;
    }
  }
}
</style>

<script>
import {
  fetchList,
  getObj,
  addObj,
  putObj,
  delObj,
  openFigerModel,
  fetchDeptTree
} from '@/api/archives'
import { IdCard } from '@/util/util'
import request from '@/router/axios'
import roleTree from '../zhgl/houseowner/roleTree.vue'
import employee from './employee'
import { getToken, setToken, removeToken } from '@/util/auth'
export default {
  name: 'table_house_owner',
  components: {
    roleTree,
    employee
  },
  data() {
    /**
     * 验证手机号
     */
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'))
      } else {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的手机号'))
        }
      }
    }
    return {
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加',
        search: '选择'
      },
      tableData: [],
      workings: [], //工作年限
      insurances: [], //是否缴纳保险
      educations: [], //学历
      positions: [], //职位
      roleSelectVisible: false,
      deleteDialog: false,
      textarea_role: '',
      textarea_role_arr: [],
      textarea_role_arr_des: [],
      uploadHeader: {
        Authorization: 'Bearer ' + getToken()
      },
      rules: {
        deviceId: [{ min: 20, max: 20, message: '设备号长度为20' }],
        name: [{ required: true, message: '请输入姓名' }],
        phone: [
          { required: true, message: '请输入手机号' },
          { validator: checkPhone, trigger: 'blur' }
        ],
        position: [{ required: true, message: '请选择职位' }],
        roleId: [{ required: true, message: '请选择角色' }],
        deptId: [{ required: true, message: '请选择部门' }],
        dsber: [
          {
            type: 'number',
            message: '请输入数字'
          }
        ]
      },
      deleteData: { quit: 1 }, //删除原因
      addFormData: {}, //表单数据
      guardLoading: false,
      treeDeptData: [],
      guardPage: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      filters: {
        name: '',
        phone: ''
      },
      addDisabled: true,
      listQuery: {
        name: '',
        phone: '',
        page: 1,
        limit: 20,
        deptId: ''
      },
      sort: {
        sort: 'sort',
        order: 'asc'
      },
      listLoading: true,
      list: null,
      total: null,
      sels: [], // 列表选中列
      idArr: [],
      uploadParams: {},
      // editFormVisible: false, // 编辑界面是否显示
      fileList: [],
      importFormVisible: false,
      editLoading: false,
      addFormVisible: false, // 新增界面是否显示
      addLoading: false,
      dialogDeptVisible: false, // IC信息维护界面是否显示
      addIcInfoLoading: false,
      addIcInfoForm: {},
      formFile: {},
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 模板下载
    templeteDown: function() {
      location.href = '/static/templates/employee.xls'
    },
    // 模板上传
    templeteUp: function() {
      this.fileList = []
      // this.uploadParams = {
      //   communityId: this.$refs.tree.getCurrentKey()
      // }
      this.importFormVisible = true
    },
    submitUpload() {
      if (this.$refs.upload.uploadFiles.length == 0) {
        this.$message({
          message: '请先选择上传的文件。',
          type: 'info',
          duration: 2000
        })
        return
      }
      console.log(this.$refs.upload.uploadFiles)
      this.addLoading = true
      this.$refs.upload.submit()
    },
    beforeAvatarUpload(file) {
      this.addLoading = false
      const isXls = file.type === 'application/vnd.ms-excel'
      const isXlsx =
        file.type ===
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isXls && !isXlsx) {
        this.$message.error('只能上传xls/xlsx文件!')
      }

      return isXls || isXlsx
    },
    handleSuccess(response, file, fileList) {
      this.addLoading = false
      if (!response.success) {
        this.$message.error(response.msg)
      } else {
        this.$message({
          message: response.msg,
          type: 'success',
          duration: 2500
        })
      }
      this.fileList = []
      this.importFormVisible = false
      // 刷新列表
      this.getList()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    idNoChange() {
      if (
        this.addFormData != undefined &&
        this.addFormData.idCard != undefined
      ) {
        if (this.addFormData.idCard.length == 18) {
          //获取性别和生日
          this.$set(this.addFormData, 'age', IdCard(this.addFormData.idCard, 3))
          this.$set(this.addFormData, 'sex', IdCard(this.addFormData.idCard, 2))
        }
      }
    },
    handleDept() {
      fetchDeptTree().then(response => {
        this.treeDeptData = response.data
      })
      this.dialogDeptVisible = true
    },
    searchDept() {
      this.dialogStatus = 'search'
      fetchDeptTree().then(response => {
        this.treeDeptData = response.data
      })
      this.dialogDeptVisible = true
    },
    closeDept() {
      this.dialogStatus = 'create'
      this.dialogDeptVisible = false
    },
    /**
     * 打开新增窗口
     */
    add() {
      this.addFormData = {}
      this.addFormVisible = true
      this.dialogStatus = 'create'
      // this.$router.push({ path: '/test/addEmployee' })
    },
    /**
     * 新增数据提交
     */
    create(formData) {
      ;(this.editLoading = true),
        this.$refs[formData].validate(valid => {
          if (!valid) return
          addObj(this.addFormData).then(res => {
            if (res.data.code === 0) {
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              this.addFormVisible = false
              this.getList()
            } else {
              this.$notify({
                title: '添加失败',
                message: res.data.msg,
                type: 'faile',
                duration: 2000
              })
            }
          })
        })
      this.editLoading = false
    },
    /**
     * 进入页面 获取列表
     */
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.tableData = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    deleteConfim(row) {
      this.deleteData.id = row.id
      this.deleteData.name = row.name
      this.deleteData.quit = '1'
      this.deleteDialog = true
    },
    /**
     * 删除表格中的某条数据
     */
    deletes() {
      this.$confirm(
        '此操作将永久删除该用户(用户名:' +
          this.deleteData.name +
          '), 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        delObj(this.deleteData.id, this.deleteData.quit)
          .then(() => {
            this.deleteDialog = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
          .cache(() => {
            this.$notify({
              title: '失败',
              message: '删除失败',
              type: 'error',
              duration: 2000
            })
          })
      })
    },
    /**
     * 打开编辑窗口
     */
    handleEdit(index, row) {
      // (this.dialogStatus = 'update'), (this.addFormVisible = true)
      // this.addFormData = row
      this.$router.push({
        path: '/archives/addEmployee',
        query: {
          id: row.id
        }
      })
    },
    /**
     * 开启指纹采集模式
     */
    handleFinger(index, row) {
      console.log(row)
      openFigerModel({ userName: row.phone, companyId: row.companyId }).then(
        res => {
          var mes = ''
          if (!this.validatenull(res.data.data.collectTime)) {
            mes = '开启成功，有效期至 ' + res.data.data.collectTime
          } else {
            mes = '该员工尚未绑定金企云微信小程序'
          }
          this.addFormVisible = false
          this.$notify({
            title: '成功',
            message: mes,
            type: 'success',
            duration: 3000
          })
        }
      )
    },
    /**
     * 修改数据
     */
    update() {
      putObj(this.addFormData).then(() => {
        this.addFormVisible = false
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    //初始化数据字典
    initDictsData: function() {
      request.get('/admin/dict/type/insurance_status').then(res => {
        if (res.status === 200) {
          this.insurances = res.data
        }
      })
      request.get('/admin/dict/type/working_status').then(res => {
        if (res.status === 200) {
          this.workings = res.data
        }
      })
      request.get('/admin/dict/type/education_status').then(res => {
        if (res.status === 200) {
          this.educations = res.data
        }
      })
      request.get('/admin/dict/type/position_status').then(res => {
        if (res.status === 200) {
          this.positions = res.data
        }
      })
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.tableData.toggleRowSelection(row)
        })
      } else {
        this.$refs.tableData.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.sels = val
    },
    handleNodeClick(data) {
      if (this.dialogStatus == 'search') {
        this.listQuery.deptId = data.id
        this.listQuery.deptName = data.name
      } else {
        this.addFormData.deptId = data.id
        this.addFormData.deptName = data.name
      }
    },
    /**
     * 重置搜索条件
     */
    resetForm() {
      this.listQuery.deptId = ''
      this.listQuery.name = ''
      this.listQuery.phone = ''
      this.getList()
    },
    /**
     * 选择角色
     */
    showRoleSelect: function() {
      this.roleSelectVisible = true
    },
    roleSelectSubmit: function() {
      this.addFormData.roleId = this.textarea_role_arr.join()
      this.addFormData.roleName = this.textarea_role
      this.roleSelectVisible = false
    },
    roleTreeNodeClick(data, node) {
      if (data.leaf) {
        var index = -1
        for (var i = 0; i < this.textarea_role_arr_des.length; i++) {
          if (this.textarea_role_arr_des[i] == data.name + '@' + data.id) {
            index = i
            break
          }
        }
        if (index >= 0) {
          this.textarea_role_arr_des.splice(index, 1)
        } else {
          this.textarea_role_arr_des.push(data.name + '@' + data.id)
        }
        var textarea_role_arr_name = []
        this.textarea_role_arr = []
        for (var i = 0; i < this.textarea_role_arr_des.length; i++) {
          var fg = this.textarea_role_arr_des[i].split('@')
          this.textarea_role_arr.push(fg[1])
          textarea_role_arr_name.push(fg[0])
        }

        this.textarea_role = textarea_role_arr_name.join()
      }
    }
  },
  watch: {},
  mounted() {
    //加载树
    this.initDictsData()
  }
}
</script>